﻿/*
 * Copyright 2012 Rene Prost, Registrite ja Infosüsteemide Keskus 
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Text;
using System.Web;
using NUnit.Framework;
using Xtee.Core.Adapter;
using Xtee.Core.Adapter.Service;
using Xtee.Core.Test.Adapter;
using System.Threading;
using Doc.Xroad.Eu;
using Xtee.XteeClient.Doc;
using HttpContextWrapper = Xtee.Core.Adapter.HttpContextWrapper;

namespace Xtee.Core.Test
{
    [Explicit]
    [TestFixture]
    public class AsyncTest : TestBase
    {


        private delegate void AsyncDelegate();
        [Test]
        public void DispatcherAsync()
        {
            var disp = new AdapterService();
            string result =
                "<?xml version=\"1.0\" encoding=\"UTF-8\"?><SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xrd=\"http://x-road.eu/xsd/xroad.xsd\" xmlns:id=\"http://x-road.eu/xsd/identifiers\"><SOAP-ENV:Header><xrd:client id:objectType=\"SUBSYSTEM\"><id:xRoadInstance>ee-dev</id:xRoadInstance><id:memberClass>GOV</id:memberClass><id:memberCode>70000310</id:memberCode><id:subsystemCode>generic-consumer</id:subsystemCode></xrd:client><xrd:service id:objectType=\"SERVICE\"><id:xRoadInstance>EE</id:xRoadInstance><id:memberClass>GOV</id:memberClass><id:memberCode>700030</id:memberCode><id:subsystemCode>Calc</id:subsystemCode><id:serviceCode>Add</id:serviceCode><id:serviceVersion>v1</id:serviceVersion></xrd:service><xrd:id>411d6755661409fed365ad8135f8210be07613da</xrd:id><xrd:userId>EE39010210022</xrd:userId><xrd:protocolVersion>4.0</xrd:protocolVersion></SOAP-ENV:Header><SOAP-ENV:Body><tns:AddResponse xmlns:tns=\"http://calculator.x-road.eu\"><request><VarX>1</VarX><VarY>1</VarY></request><Result><Value>2</Value></Result></tns:AddResponse></SOAP-ENV:Body></SOAP-ENV:Envelope>";

            AsyncDelegate asyncOperation = delegate
            {

                string xxxx = @"<?xml version='1.0' encoding='UTF-8'?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV='http://schemas.xmlsoap.org/soap/envelope/' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xrd='http://x-road.eu/xsd/xroad.xsd' xmlns:id='http://x-road.eu/xsd/identifiers' xmlns:tns='http://calculator.x-road.eu'>
<SOAP-ENV:Header>
<xrd:client id:objectType='SUBSYSTEM'>
 <id:xRoadInstance>ee-dev</id:xRoadInstance>
 <id:memberClass>GOV</id:memberClass>
 <id:memberCode>70000310</id:memberCode>
<id:subsystemCode>generic-consumer</id:subsystemCode>
 </xrd:client>
 <xrd:service id:objectType='SERVICE'>
 <id:xRoadInstance>EE</id:xRoadInstance>
 <id:memberClass>GOV</id:memberClass>
 <id:memberCode>700030</id:memberCode>
<id:subsystemCode>Calc</id:subsystemCode>
 <id:serviceCode>Add</id:serviceCode>
<id:serviceVersion>v1</id:serviceVersion>
 </xrd:service>
 <xrd:id>411d6755661409fed365ad8135f8210be07613da</xrd:id>
<xrd:userId>EE39010210022</xrd:userId>
 <xrd:protocolVersion>4.0</xrd:protocolVersion>
</SOAP-ENV:Header>
<SOAP-ENV:Body>
<tns:Add>
<request >
<VarX>1</VarX>
<VarY>1</VarY>
</request>
</tns:Add>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>";
               
                using (var wrapper = new HttpContextWrapper(new MemoryStream(Encoding.UTF8.GetBytes(xxxx)),new NameValueCollection(),Configurator.GetConfig()))
                {
                    disp.Serve(wrapper);
                    wrapper.ResponseStream.Position = 0;
                    string data = new StreamReader(wrapper.ResponseStream).ReadToEnd();
                    Assert.AreEqual(result, data);
                }
               

            };

            IList<IAsyncResult> begin = new List<IAsyncResult>();
            for (int x = 0; x <= 1000; x++)
                begin.Add(asyncOperation.BeginInvoke(null, null));

            for (int x = 0; x <= 1000; x++)
                asyncOperation.EndInvoke(begin[x]); 
            
        }

        [Test]
        public void XteeHttpHandlerAsync_ListMethods()
        {

            var handler = new XteeServiceHttpHandler(); 
            

            AsyncDelegate asyncOperation = delegate
            {

             
                StringWriter outputData = new StringWriter();
                HttpContext context = GetTestContext(File.ReadAllText(@"../../ResourceData/listMethods.xml"), "text/xml", outputData);
                handler.ProcessRequest(context); 
                context.Response.Flush();
                string result = outputData.ToString();

                Assert.IsTrue(result.Contains("<id:serviceCode>Add</id:serviceCode>"));

            };

            IList<IAsyncResult> begin = new List<IAsyncResult>();
            for (int x = 0; x <= 1000; x++)
            {
                begin.Add(asyncOperation.BeginInvoke(null, null));
             
            }

            for (int x = 0; x <= 1000; x++)
            {
                asyncOperation.EndInvoke(begin[x]);
             
            } 
        }
        
        [Test]

        public void TestDoc_Attachment_Async()
        {
            var adapter = new DocAdapter();

            adapter.XteeCommand.Configuration.ProxyURL = new Uri("http://localhost:6007/AdapterXtee.asmx");

            AsyncDelegate asyncOperation = delegate
          {
              
              string filename = @"C:\TEMP\OfDocumentServer\ullalla" + Thread.CurrentThread.ManagedThreadId;
              if (File.Exists(filename))
                  File.Delete(filename);

              adapter.AddDocument(new Document("ullalla" + Thread.CurrentThread.ManagedThreadId, new FileInfo(@"../../ResourceData/funny_cät_problem.jpg"))
                  );
              var returnFile = adapter.GetDocument("ullalla" + Thread.CurrentThread.ManagedThreadId).Document.Sisu;
              FileInfo sentFile = new FileInfo(filename);
              Assert.AreEqual(returnFile.Length, sentFile.Length);
          };

            IList<IAsyncResult> begin = new List<IAsyncResult>();
            for (int x = 0; x <= 100; x++)
            {

                begin.Add(asyncOperation.BeginInvoke(null, null));
            }

            for (int x = 0; x <= 100; x++)
            {

                asyncOperation.EndInvoke(begin[x]);
            } 
            
        }


    }
}
